<template>
  <div class="form-container">
    <el-form inline class="form-inline" :model="params" ref="refParams" label-width="70">
      <el-form-item label="选择城市" prop="city">
        <el-select size="default" v-model="params.city" placeholder="请选择城市">
          <el-option v-for="item in cityOptions" :key="item.cityId" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="配送员" prop="deliveryId">
        <el-select size="default" v-model="params.deliveryId" placeholder="请选择配送员">
          <el-option v-for="item in deliveryList" :key="item.userId" :label="item.fullName" :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间类型" prop="type">
        <el-select size="default" v-model="params.type" placeholder="请选择类型">
          <el-option label="按天" value="2"></el-option>
          <el-option label="按月" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="date-container" label="开始时间" prop="startTime">
        <el-date-picker
          v-model="params.startTime"
          type="datetime"
          placeholder="开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="MMM DD, YYYY"
          time-format="HH:mm"
        />
        <!-- <el-date-picker
          v-model="timeVal"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="hh:mm:ss"
          :disabled-date="handleDisabledDate"
        /> -->
      </el-form-item>
      <el-form-item class="date-container" label="结束时间" prop="endTime">
        <el-date-picker
          v-model="params.endTime"
          type="datetime"
          placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="MMM DD, YYYY"
          time-format="HH:mm:ss"
          :disabled-date="handleDisabledDate"
        />
        <!-- <el-date-picker
          v-model="timeVal"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="hh:mm:ss"
          :disabled-date="handleDisabledDate"
        /> -->
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleReset(refParams as FormInstance)">重置</el-button>
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>
  </div>
  <div class="numContent">
    <h5>订单统计</h5>
    <div class="dStatistics">
      <span>订单总数:{{ dataList?.ordersTotal }}</span>
      <span>超时送达率:{{ dataList?.timeoutDeliveryRate }}</span>
      <span>正常送达率:{{ dataList?.normalDeliveryRate }}</span>
      <span>平均拣货耗时:{{ dataList?.averagePickingTime }}</span>
      <span>平均配送耗时:{{ dataList?.averageDistributionTime }}</span>
      <span>出单平均间隔时长:{{ dataList?.averageIntervalBetweenOrders }}</span>
    </div>
  </div>
  <div class="chartContent">
    <div ref="chartContainer" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script setup lang="ts" name="lineChart">
import dayjs from "dayjs";
import { Static } from "@/api/interface/static";
import { getDeliveryStatisticsAPI } from "@/api/modules/staticAPI";
import { ECOption } from "@/components/ECharts/config";
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import { ElMessage, FormInstance } from "element-plus";
import { getCityListDictAPI } from "@/api/modules/dictAPI";
import { Dict } from "@/api/interface/dict";
import { getNewRegisterAPI } from "@/api/modules/city/organizationAPI";
import { Delivery } from "@/api/interface/city/organizationManage";
let chart = ref<any>();
const chartContainer = ref<HTMLDivElement>();
// const timeVal = ref<string[]>([]);
const refParams = ref<FormInstance>();
const handleReset = (elForm: FormInstance) => {
  elForm.resetFields();
};
const handleSearch = () => {
  if (params.value.startTime && params.value.endTime) {
    params.value.startTime = dayjs(params.value.startTime).format("YYYY-MM-DD HH:mm:ss");
    params.value.endTime = dayjs(params.value.endTime).format("YYYY-MM-DD HH:mm:ss");
  }
  getDeliveryStatistics();
};
const option = ref<ECOption>({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      label: {
        backgroundColor: "#6a7985"
      }
    }
  },
  legend: {
    data: ["Email", "Union Ads", "Video Ads", "Direct", "Search Engine"],
    top: "bottom",
    textStyle: {
      color: "#a1a1a1"
    }
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  xAxis: [
    {
      type: "category",
      boundaryGap: false,
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      axisLabel: {
        color: "#a1a1a1"
      }
    }
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {
        color: "#a1a1a1"
      }
    }
  ],
  series: [
    {
      name: "Email",
      type: "line",
      stack: "Total",
      areaStyle: {},
      emphasis: {
        focus: "series"
      },
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: "Union Ads",
      type: "line",
      stack: "Total",
      areaStyle: {},
      emphasis: {
        focus: "series"
      },
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: "Video Ads",
      type: "line",
      stack: "Total",
      areaStyle: {},
      emphasis: {
        focus: "series"
      },
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: "Direct",
      type: "line",
      stack: "Total",
      areaStyle: {},
      emphasis: {
        focus: "series"
      },
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: "Search Engine",
      type: "line",
      stack: "Total",
      label: {
        show: true,
        position: "top"
      },
      areaStyle: {},
      emphasis: {
        focus: "series"
      },
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    }
  ]
});
const params = ref<Static.ADDParams>({
  startTime: dayjs().subtract(7, "day").format("YYYY-MM-DD HH:mm:ss"),
  endTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  type: "2"
});
const handleDisabledDate = (date: Date) => {
  // const firstTime = ref<number>(Date.now());
  const firstTime = ref<number>();
  firstTime.value = dayjs(params.value.startTime).valueOf();
  // console.log(firstTime.value, params.value.startTime);

  if (params.value.type == "2") {
    console.log("进入按月查询");
    // return true;
    return date.getTime() < firstTime.value || date.getTime() > firstTime.value + 24 * 60 * 60 * 1000 * 30;
  } else {
    return date < new Date(firstTime.value) || date > new Date(firstTime.value + 24 * 60 * 60 * 1000 * 365);
  }
};
const getDeliveryStatistics = async () => {
  const { data, code, msg } = await getDeliveryStatisticsAPI(params.value);
  if (code == "200" && data) {
    console.log(data);
    dataList.value = data;
    const legendData = data.statistics.map(item => item.stationName);
    const xData = data.statistics[0].data.map(item => item.data);
    const seriesData = data.statistics.map(item => {
      return {
        name: item.stationName,
        type: "line",
        stack: "Total",
        label: {
          show: true,
          position: "top"
        },
        areaStyle: {},
        emphasis: {
          focus: "series"
        },
        data: item.data.map(item => item.num)
      };
    });
    Object.assign(option.value, {
      legend: {
        data: legendData
      },
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          data: xData,
          axisLabel: {
            color: "#a1a1a1"
          }
        }
      ],
      series: seriesData
    });
    chart.value.setOption(option.value);
    console.log(option.value);
  } else {
    console.log(msg);
  }
};
const dataList = ref<Static.Data>();
const cityOptions = ref<Dict.CityListData[]>([]);
const getCityListDict = async () => {
  const { data, code } = await getCityListDictAPI({
    parentCode: JSON.parse(localStorage.getItem("userInfo") as string).province
  });
  if (code == "200" && data) {
    cityOptions.value = data;
  } else {
    ElMessage.error("获取城市列表失败");
  }
};
const deliveryList = ref<Delivery.NewRow[]>([]);
const getDeliveryListData = async () => {
  const { rows, code, msg } = await getNewRegisterAPI({
    fullName: "",
    auditStatus: "2",
    delFlag: "0",
    province: JSON.parse(localStorage.getItem("userInfo") as string).province,
    city: JSON.parse(localStorage.getItem("userInfo") as string).city,
    pageNum: 1,
    pageSize: 100
  });
  if (code == "200" && rows) {
    deliveryList.value = rows;
  } else {
    ElMessage.error(`获取失败,${msg}`);
  }
};
onMounted(() => {
  chart.value = echarts.init(chartContainer.value);
  console.log("echarts", chart);
  getDeliveryStatistics();
  getCityListDict();
  getDeliveryListData();
});
</script>

<style scoped lang="scss">
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
    ::v-deep .el-button > span {
      font-size: 13px;
    }
  }
  .el-form {
    display: inline-block;
    ::v-deep .el-form-item__label {
      font-size: 13px;
    }
  }
  .form-line {
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.numContent {
  padding: 15px;
  background-color: white;
  .dStatistics {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    span {
      margin-right: 10px;
      font-size: 13px;
      font-weight: 400;
      color: #666666;
    }
  }
}
.chartContent {
  padding: 15px;
  margin-top: 5px;
  background: white;
}
.el-form-item {
  width: 200px;
  margin: 0;

  // margin-right: 20px;
}
.date-container {
  width: 250px;
}
</style>
